import { Tabs, Card, Form, message } from 'antd';
import React, { FC, useState, useEffect } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import BaseInfo from './baseInfo';
import { history } from 'umi';
import { createRule, updateRule } from '../service';
import Price from './price';
import { detailRule } from '../service';

const { TabPane } = Tabs;

type InternalNamePath = (string | number)[];
interface StateData {
  detail: any;
  submitting: boolean;
}

interface ErrorField {
  name: InternalNamePath;
  errors: string[];
}

interface AdvancedFormProps { }

const Goods: FC<AdvancedFormProps> = (props: any) => {

  const [form] = Form.useForm();
  const { setFieldsValue } = form;
  const [state, setState] = useState<StateData>({
    detail: {},
    submitting: false
  });

  const [error, setError] = useState<ErrorField[]>([]);

  useEffect(() => {
    setFieldsValue(detail);
  }, []);

  const { submitting } = state;


  const { detail } = state;

  useEffect(() => {
    const {
      match: {
        params: { id },
      },
    } = props;
    if (id) {
      detailRule({ id }).then(({ code, data }) => {
        if (code === 0) {
          setState({
            ...state,
            detail: data,
          });
        }
      });
    }
  }, []);

  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
  };



  const onFinish = async (values: { [key: string]: any }) => {
    setError([]);
    setState({ ...state, submitting: true });

    let result = null;
    const {
      match: {
        params: { id },
      },
    } = props;
    if (id) {
      result = await updateRule(id, values);
    } else {
      result = await createRule(values);
    }

    setState({ ...state, submitting: false });
    if (result.code === 0) {
      message.success('操作成功');
      setTimeout(() => {
        history.push({ pathname: '/goods/list' });
      }, 500);
    }
  };
  const baseProps = {
    ...props,
    detail,
    form,
    submitting,
    layout,
    onFinish
  };

  return (
    <PageHeaderWrapper>
      <Card>
        <Form
          style={{ width: 600 }}
          {...layout}
          form={form}
          layout="horizontal"
          initialValues={detail}
          onFinish={onFinish}
        >
          <Tabs defaultActiveKey="0">
            <TabPane tab="商品信息" key="0">
              <BaseInfo {...baseProps} />
            </TabPane>
            <TabPane tab="规格/价格/库存" key="1">
              <Price {...baseProps} />
            </TabPane>
          </Tabs>
        </Form>
      </Card>
    </PageHeaderWrapper>
  );
};

export default Goods;
